//
//  HHSwitchTableListCell.m
//  developKit
//
//  Created by Hayder on 2022/12/18.
//

#import "HHSwitchTableListCell.h"

@implementation HHSwitchTableListCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
    {
        [self.blankView addSubview:self.titleLabel];
        [self.blankView addSubview:self.switchBtn];
    }
    return self;
}

- (void)setItem:(HHSwitchListItem *)item
{
    _item = item;
    
    [self setConfigWithItem:item];
    
    self.titleLabel.text = item.title;
    self.switchBtn.on = item.isOn;
    
    [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat contentW = self.blankView.width;
    CGFloat contentH = self.blankView.height;
    
    self.switchBtn.frame = CGRectMake(contentW - self.margin - 51, 9.5, 51, (contentH - 31)/2);
    self.titleLabel.frame = CGRectMake(self.margin, 0, self.switchBtn.left - 2*self.margin, contentH);
}

- (UILabel *)titleLabel
{
    if(!_titleLabel)
    {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = Font(15);
        _titleLabel.textColor = kGray_51;
    }
    return _titleLabel;
}

- (UISwitch *)switchBtn
{
    if(!_switchBtn)
    {
        UISwitch *s = [[UISwitch alloc] init];
        [s addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:s];
        _switchBtn = s;
    }
    
    return _switchBtn;
}

- (void)switchChanged:(UISwitch *)swithOn
{
    self.item.isOn = swithOn.isOn;
    if(self.item.didClickSwitchBlock)
    {
        self.item.didClickSwitchBlock(swithOn.isOn);
    }
}

@end
